//
//  DR_EnterPasswordSheet.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import SnapKit

class DR_EnterPasswordSheet: UIView {
    
    var onCancel: (() -> Void)?
    var onConfirm: ((String) -> Void)?
    
    private let backgroundView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        return view
    }()
    
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 20
        view.layer.masksToBounds = true
        return view
    }()
    
    private let fileIconView: UIImageView = {
        let imageView = UIImageView()
        // 使用带锁的文件夹图标，如果没有可以用系统图标组合
        imageView.image = UIImage(named: "home_lock") // 或者使用系统图标
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let fileNameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        label.numberOfLines = 2
        return label
    }()
    
    private let fileSizeLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 14)
        label.textColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
        label.textAlignment = .center
        return label
    }()
    
    private let textFieldContainer: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 12
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).cgColor
        return view
    }()
    
    private let textField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "Please Enter Your Password"
        textField.font = UIFont.systemFont(ofSize: 14)
        textField.textColor = .black
        textField.isSecureTextEntry = true
        textField.clearButtonMode = .never
        return textField
    }()
    
    private let clearButton: UIButton = {
        let button = UIButton(type: .custom)
        let xmarkImage = UIImage(systemName: "xmark.circle.fill")
        button.setImage(xmarkImage, for: .normal)
        button.tintColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1.0)
        button.isHidden = true
        return button
    }()
    
    private let errorStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.spacing = 6
        stackView.alignment = .center
        stackView.isHidden = true
        return stackView
    }()
    
    private let errorIconView: UIImageView = {
        let imageView = UIImageView()
        let errorIcon = UIImage(systemName: "exclamationmark.circle.fill")
        imageView.image = errorIcon
        imageView.tintColor = .red
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let errorLabel: UILabel = {
        let label = UILabel()
        label.text = "Password Error"
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = .red
        return label
    }()
    
    private let buttonsStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = 12
        return stackView
    }()
    
    private let cancelButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("Cancel", for: .normal)
        button.setTitleColor("#333FFF".toColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = .white
        button.layer.cornerRadius = 12
        button.layer.borderWidth = 1
        button.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).cgColor
        return button
    }()
    
    private let confirmButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("Unlock", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = "#333FFF".toColor
        button.layer.cornerRadius = 12
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
        setupActions()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(backgroundView)
        addSubview(containerView)
        
        containerView.addSubview(fileIconView)
        containerView.addSubview(fileNameLabel)
        containerView.addSubview(fileSizeLabel)
        containerView.addSubview(textFieldContainer)
        textFieldContainer.addSubview(textField)
        textFieldContainer.addSubview(clearButton)
        containerView.addSubview(errorStackView)
        errorStackView.addArrangedSubview(errorIconView)
        errorStackView.addArrangedSubview(errorLabel)
        containerView.addSubview(buttonsStackView)
        
        buttonsStackView.addArrangedSubview(cancelButton)
        buttonsStackView.addArrangedSubview(confirmButton)
    }
    
    private func setupConstraints() {
        backgroundView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        containerView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
            make.width.equalTo(320)
        }
        
        fileIconView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(24)
            make.width.height.equalTo(60)
        }
        
        fileNameLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(fileIconView.snp.bottom).offset(16)
        }
        
        fileSizeLabel.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(fileNameLabel.snp.bottom).offset(8)
        }
        
        textFieldContainer.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(fileSizeLabel.snp.bottom).offset(20)
            make.height.equalTo(50)
        }
        
        textField.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.trailing.equalTo(clearButton.snp.leading).offset(-8)
            make.centerY.equalToSuperview()
        }
        
        clearButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(20)
        }
        
        errorStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(textFieldContainer.snp.bottom).offset(8)
        }
        
        errorIconView.snp.makeConstraints { make in
            make.width.height.equalTo(16)
        }
        
        buttonsStackView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.top.equalTo(errorStackView.snp.bottom).offset(12)
            make.height.equalTo(50)
            make.bottom.equalToSuperview().offset(-24)
        }
    }
    
    private func setupActions() {
        backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cancelTapped)))
        cancelButton.addTarget(self, action: #selector(cancelTapped), for: .touchUpInside)
        confirmButton.addTarget(self, action: #selector(confirmTapped), for: .touchUpInside)
        clearButton.addTarget(self, action: #selector(clearTextField), for: .touchUpInside)
        
        textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
    }
    
    // MARK: - 配置文件信息
    func configure(fileName: String, fileSize: String) {
        fileNameLabel.text = fileName.uppercased()
        fileSizeLabel.text = fileSize
    }
    
    @objc private func cancelTapped() {
        hide()
        onCancel?()
    }
    
    @objc private func confirmTapped() {
        guard let text = textField.text, !text.trimmingCharacters(in: .whitespaces).isEmpty else {
            return
        }
        onConfirm?(text.trimmingCharacters(in: .whitespaces))
    }
    
    @objc private func clearTextField() {
        textField.text = ""
        clearButton.isHidden = true
        errorStackView.isHidden = true
    }
    
    @objc private func textFieldDidChange() {
        clearButton.isHidden = textField.text?.isEmpty ?? true
        errorStackView.isHidden = true
    }
    
    // MARK: - 显示错误信息
    func showError() {
        errorStackView.isHidden = false
        textField.text = ""
        clearButton.isHidden = true
    }
    
    // MARK: - 显示和隐藏
    func show(in parentView: UIView) {
        parentView.addSubview(self)
        parentView.bringSubviewToFront(self)
        
        self.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            self.topAnchor.constraint(equalTo: parentView.topAnchor),
            self.leadingAnchor.constraint(equalTo: parentView.leadingAnchor),
            self.trailingAnchor.constraint(equalTo: parentView.trailingAnchor),
            self.bottomAnchor.constraint(equalTo: parentView.bottomAnchor)
        ])
        
        // 初始状态：背景透明，容器缩放
        backgroundView.alpha = 0
        containerView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        
        // 强制布局
        layoutIfNeeded()
        
        // 动画显示
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut) {
            self.backgroundView.alpha = 1
            self.containerView.transform = .identity
        } completion: { _ in
            // 显示后自动聚焦输入框
            self.textField.becomeFirstResponder()
        }
    }
    
    func hide() {
        textField.resignFirstResponder()
        UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn) {
            self.backgroundView.alpha = 0
            self.containerView.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
        } completion: { _ in
            self.removeFromSuperview()
        }
    }
}
